public class Solution92 {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode reverseBetween(ListNode head, int left, int right) {
        if (left==right){
            return head;
        }
        ListNode first=new ListNode(-1,head);
        ListNode f=first;
        for (int i=0;i<left-1;i++){
            f=f.next;
        }
        ListNode le=f;
        f=f.next;
        ListNode len=f;
        ListNode p=f.next;
        ListNode n=p.next;
        for (int i=0;i<right-left;i++){
            p.next=f;
            f=p;
            p=n;
            if (n!=null) {
                n=n.next;
            }
        }
        le.next=f;
        len.next=p;
        return first.next;
    }

    public static void main(String[] args) {
        System.out.println(new Solution92().reverseBetween(new ListNode(1,new ListNode(2,new ListNode(3,new ListNode(4,new ListNode(5))))),1,5).next.val);
    }
}
